package sk.naive.talker.props;

import sk.naive.talker.util.PropertyConfiguration;

import java.util.*;

/**
 * AbstractPropertyStore.
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.5 $ $Date: 2007-05-07 10:34:20 $
 */
public final class PropertyStoreImpl {
	private Map<String,Object> properties;
	private PropertyConfiguration propertyConfiguration;

	public PropertyStoreImpl(PropertyConfiguration propertyConfiguration) {
		this.propertyConfiguration = propertyConfiguration;
		properties = new HashMap<String,Object>();
	}

	public void set(String property, Object value)
		throws PropertyStoreException
	{
		testValidValue(property, value);
		properties.put(property, value);
	}

	public Map<String,Object> getProperties() {
		return properties;
	}

	private void testValidValue(String property, Object value) throws InvalidPropertyValueException {
		Property p = getProperty(property);
		if (p != null) {
			if (!p.checkValue(value)) {
				throw new InvalidPropertyValueException("Invalid value '" + value + "' for property " + property + ".");
			}
		}
	}

	public Object get(String key) {
		Object rval = properties.get(key);
		if (rval == null) {
			return getProperty(key).defaultValue();
		}
		return rval;
	}

	public Property getProperty(String key) {
		if (propertyConfiguration == null) {
			return SimpleProperty.INSTANCE;
		}
		return propertyConfiguration.getProperty(key);
	}

	public Set<String> getSettable() {
		if (propertyConfiguration == null) {
			return null;
		}
		return propertyConfiguration.getSettable();
	}

	public Set<String> getPersistent() {
		if (propertyConfiguration == null) {
			return null;
		}
		return propertyConfiguration.getPersistent();
	}

	public Set<String> getGlobal() {
		if (propertyConfiguration == null) {
			return null;
		}
		return propertyConfiguration.getGlobal();
	}

	public PropertyConfiguration getPropertyConfiguration() {
		return propertyConfiguration;
	}
}
